<template>
  <div>
    <a-card title="销售开单">
      <a-spin :spinning="loading">
        <a-form-model ref="form" :model="form" :rules="rules" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
          <a-row>
            <a-col :span="6" style="width: 320px;">
              <a-form-model-item prop="number" label="销售编号">
                <a-input v-model="form.number" />
              </a-form-model-item>
            </a-col>
            <a-col :span="6" style="width: 320px;">
              <a-form-model-item prop="warehouse" label="仓库">
                <a-select v-model="form.warehouse" style="width: 100%">
                  <a-select-option v-for="item in warehouseItems" :key="item.id" :value="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="6" style="width: 320px;">
              <a-form-model-item prop="client" label="客户" >
                <a-select showSearch v-model="form.client" style="width: 100%" :filterOption="filterOption">
                  <a-select-option v-for="item in clientsItems" :key="item.id" :value="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="6" style="width: 320px;">
              <a-form-model-item prop="handler" label="经手人">
                <a-select v-model="form.handler" style="width: 100%">
                  <a-select-option v-for="item in handlerItems" :key="item.id" :value="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="6" style="width: 320px;">
              <a-form-model-item prop="handle_time" label="处理日期">
                <!-- <a-date-picker v-model="form.handle_time" valueFormat="YYYY-MM-DD" style="width: 100%" /> -->
                <a-date-picker v-model="form.handle_time" valueFormat="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
              </a-form-model-item>
            </a-col>
            <!-- <a-col :span="6" style="width: 320px;">
              <a-form-model-item prop="discount" label="整单折扣">
                <a-input-number v-model="form.discount" style="width: 100%;" />
              </a-form-model-item>
            </a-col>
            <a-col :span="6" style="width: 320px;">
              <a-form-model-item prop="other_amount" label="其他费用">
                <a-input-number v-model="form.other_amount" style="width: 100%;" />
              </a-form-model-item>
            </a-col> -->
            <a-col :span="6" style="width: 320px;">
              <a-form-model-item prop="remark" label="备注">
                <a-input v-model="form.remark" allowClear />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>

        <a-divider orientation="left">产品信息</a-divider>

        <div>
          <a-row gutter="16">
            <a-space>
              <a-button type="primary" @click="openMaterialModal">添加产品</a-button>
            </a-space>
          </a-row>
          <div style="margin-top: 16px;">
            <a-table bordered rowKey="id" size="middle" :columns="columns" :data-source="goodsData" :pagination="false">
              <div slot="chicun" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>                
                <a-input v-else v-model="item.chicun" :min="0" size="small" placeholder="" bordered={false} ></a-input>
              </div>
              <div slot="huchang" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>                
                <a-input v-else v-model="item.huchang" :min="0" size="small" placeholder="" bordered={false} ></a-input>
              </div>
              <div slot="clsl" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input-number v-else v-model="item.clsl" :min="0" size="small"></a-input-number>
              </div>
              <div slot="cldj" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input-number v-else v-model="item.cldj" :min="0" size="small"></a-input-number>
              </div>
              <div slot="clAmount" slot-scope="value, item, index">
                <div>{{ value?1:0 }}</div>                
              </div>
              <div slot="jgsl" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input-number v-else v-model="item.jgsl" :min="0" size="small"></a-input-number>
              </div>
              <div slot="jgdj" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input-number v-else v-model="item.jgdj" :min="0" size="small"></a-input-number>
              </div>
              <div slot="jgAmount" slot-scope="value, item, index">
                <div>{{ value }}</div>                
              </div>
              <div slot="totalAmount" slot-scope="value, item, index">
                <div>{{ value }}</div>
              </div>
              <div slot="beizhu" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input v-else v-model="item.beizhu" :min="0" size="small" placeholder="" bordered={false} ></a-input>
              </div>
              <div slot="action" slot-scope="value, item, index">
                <a-button-group v-if="!item.isTotal" size="small">
                  <a-button type="danger" @click="removeMaterial(item)">移除</a-button>
                </a-button-group>
              </div>
            </a-table>
          </div>
        </div>
        <a-divider orientation="left">账单信息</a-divider>
        <div>
          <a-row gutter="16">
            <a-col :span="4">
              <a-form-model-item prop="discount" label="整单折扣" :label-col="{ span: 24 }" :wrapper-col="{ span: 24 }">
                <a-input-number v-model="form.discount" style="width: 100%;" />
              </a-form-model-item>
            </a-col>

            <a-col :span="4">
              <a-form-model-item
                prop="other_amount"
                label="其他费用"
                :label-col="{ span: 24 }"
                :wrapper-col="{ span: 24 }"
              >
                <a-input-number v-model="form.other_amount" style="width: 100%;" />
              </a-form-model-item>
            </a-col>
            <a-col :span="4">
              <a-form-model-item label="总计金额(元)" :label-col="{ span: 24 }" :wrapper-col="{ span: 24 }">
                <a-input-number :value="totalAmount" :disabled="true" style="width: 100%;" />
              </a-form-model-item>
            </a-col>
            <a-col :span="4">
              <a-form-model-item label="总计金额(大写)" :label-col="{ span: 24 }" :wrapper-col="{ span: 24 }">
                <a-input-number :value="convertCurrency(totalAmount)" :disabled="true" style="width: 100%;color:black;" />
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row gutter="16">
            <a-col :span="4">
              <a-form-model-item label="结算账户" :label-col="{ span: 24 }" :wrapper-col="{ span: 24 }">
                <a-select v-model="sales_account_item.account" style="width: 100%">
                  <a-select-option v-for="Account in accountsItems" :key="Account.id" :value="Account.id">
                    {{ Account.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="4">
              <a-form-model-item label="实收金额(元)" :label-col="{ span: 24 }" :wrapper-col="{ span: 24 }">
                <a-input-number v-model="sales_account_item.collection_amount" style="width: 100%;" />
              </a-form-model-item>
            </a-col>
            <a-col :span="4">
              <a-form-model-item label="本单欠款(元)" :label-col="{ span: 24 }" :wrapper-col="{ span: 24 }">
                <a-input-number :value="amountOwed" :disabled="true" style="width: 100%;" />
              </a-form-model-item>
            </a-col>
            <a-col :span="4">
              <a-form-model-item label="欠款金额(大写)" :label-col="{ span: 24 }" :wrapper-col="{ span: 24 }">
                <a-input-number :value="convertCurrency(amountOwed)" :disabled="true" style="width: 100%;color:black;" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <!-- <a-row gutter="16">
            <a-col :span="4">
              <a-form-model-item label="本单欠款(元)" :label-col="{ span: 24 }" :wrapper-col="{ span: 24 }">
                <a-input-number :value="amountOwed" :disabled="true" style="width: 100%;" />
              </a-form-model-item>
            </a-col>
          </a-row> -->
        </div>
    
      </a-spin>

      <div style="margin-top: 10px;">
        <a-popconfirm title="确定开单吗?" @confirm="create">
          <a-button type="primary" :loading="loading">开单</a-button>
        </a-popconfirm>
      </div>
    </a-card>
      <!-- v-model="materialsSelectModalVisible" -->
    <materials-select-modal    
      v-model="materialsSelectModalVisible"
      :warehouse="form.warehouse"
      @select="onSelectMaterial"
    ></materials-select-modal>
  </div>
</template>

<script>
import moment from "moment";
import { getSaleOrderNumber } from "@/api/data";
import { saleOrderCreate } from "@/api/sale";
import { convertCurrency,datetimeToString } from '@/utils/functions';
import { userOption, clientsOption, warehousesOption, inventoriesOption, accountsOption } from "@/api/option";
import {columns,columns_dagong,rules,columnsAccount} from "@/views/sale/saleCreate/js/data";

export default {
  components: {
    MaterialsSelectModal: () => import("@/components/MaterialSelectModal/index"),
  },
  data() {
    return {
      description: "新增",
      warehouseItems: [],
      handlerItems: [],
      clientsItems: [],
      accountsItems: [],
      materialsSelectModalVisible: false,
      loading: false,
      model: {},
      form: {
        warehouse:'原材料仓库'
      },
      rules,
      columns,
      columns_dagong,
      materialItems: [],
      columnsAccount,
      sales_account_items: [],
      sales_account_item: {},
    };
  },
  computed: {
    totalAmount() {
      let totalAmount = 0;
      for (let item of this.materialItems) {
        // let amount = NP.times(item.sales_quantity, item.sales_price);
        let amount = NP.plus( NP.times(item.clsl, item.cldj), NP.times(item.jgsl, item.jgdj));
        totalAmount = NP.plus(totalAmount, amount);
      }

      totalAmount = NP.times(totalAmount, this.form.discount || 100, 0.01);
      totalAmount = NP.plus(totalAmount, this.form.other_amount || 0);
      return totalAmount;
    },
    amountOwed() {
      return NP.minus(this.totalAmount, this.sales_account_item.collection_amount || 0);
    },
    goodsData() {
      // 统计合计
      let totalclAmount = 0,
        clAmount = 0,
        jgAmount = 0,
        totaljgAmount = 0,
        totalAmount =0;
      // for (let item of this.materialItems) {
      //   totalQuantity = NP.plus(totalQuantity, item.sales_quantity);
      //   let amount = NP.times(item.sales_quantity, item.sales_price);
      //   totalAmount = NP.plus(totalAmount, amount);
      // }
      for (let item of this.materialItems) {
        totalclAmount = NP.times(item.clsl, item.cldj)
        totaljgAmount = NP.times(item.jgsl, item.jgdj)
        clAmount = NP.plus(clAmount,totalclAmount);
        jgAmount = NP.plus(jgAmount,totaljgAmount);
        totalAmount = NP.plus(totalAmount,totalclAmount, totaljgAmount);
      }
      return [
        ...this.materialItems,
        {
          id: "-1",
          isTotal: true,
          name: "",
          // sales_quantity: totalQuantity,
          // totalAmount: `${totalAmount} * ${this.form.discount}% = ${NP.times(
          //   totalAmount,
          //   this.form.discount || 0,
          //   0.01
          // )}`,
          clAmount,
          jgAmount,
          totalAmount,
        },
      ];
    },
    accountsData() {
      // 统计合计
      let totalAmount = 0;
      for (let item of this.sales_account_items) {
        totalAmount = NP.plus(totalAmount, item.collection_amount);
      }
      return [
        ...this.sales_account_items,
        {
          id: "-1",
          isTotal: true,
          collection_amount: totalAmount,
        },
      ];
    },
  },
  methods: {  
  // 将输入的内容与显示的内容进行匹配
  filterOption (value, option) {
      return option.componentOptions.children[0].text.indexOf(value) >= 0
    },
  convertCurrency(money){
      return convertCurrency(money)
    },
    initData() {
      this.resetForm();
      warehousesOption({ page_size: 999999, is_active: true }).then((data) => {
        this.warehouseItems = data.results;
        this.form.warehouse = this.warehouseItems[0].id
      });
      userOption({ page_size: 999999, is_active: true }).then((data) => {
        this.handlerItems = data.results;
      });
      clientsOption({ page_size: 999999, is_active: true }).then((data) => {
        this.clientsItems = data.results;
      });
      accountsOption({ page_size: 999999, is_active: true }).then((data) => {
        this.accountsItems = data.results;
      });
      this.form.handle_time=datetimeToString(new Date())
    },
    handelAddAcount() {
      this.sales_account_items.push({
        id: this.sales_account_items.length + 1,
        account: "",
        collection_amount: 0,
      });
    },
    removeAccount(item) {
      this.sales_account_items = this.$functions.removeItem(this.sales_account_items, item);
    },
    changeAccount(value, item, idx) {
      let count = this.sales_account_items.filter((_item) => {
        return _item.account == value;
      });
      if (count.length > 1) {
        this.$message.warn("已添加过改结算账户!");
        this.sales_account_items[idx].account = "";
      }
    },
    openMaterialModal() {
      if (!this.form.warehouse) {
        this.$message.warn("请先选择仓库！");
        return false;
      }
      this.materialsSelectModalVisible = true;
      console.log("this.materialsSelectModalVisible ",this.materialsSelectModalVisible)
    },
    onSelectMaterial(item) {
      let index = this.materialItems.findIndex((_item) => _item.id == item.id);

      // if (index != -1) {
      //   this.$message.warn("产品已存在");
      //   return;
      // }
      console.log(item)
      this.materialItems = this.$functions.insertItem(this.materialItems, {
        id: item.id,
        goods: item.goods,
        number: item.goods_number,
        name: item.goods_name,
        guige: item.goods_spec,
        chicun: "",
        huchang: "",
        clsl: 0,
        cldj: 0,
        clAmount: 0,
        jgsl: 0,
        jgdj: 0,
        jgAmount: 0,
        beizhu: "",
        unit: item.unit_name,
        sales_quantity: 1,
        sales_price: item.retail_price,
        totalAmount: 1,
      });

      this.materialItems = [...this.materialItems];
      console.log("this.materialItems:",this.materialItems);
    },
    removeMaterial(item) {
      this.materialItems = this.$functions.removeItem(this.materialItems, item);
    },
    create() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          let ifHasEmptyGoods = false;
          let ifHasEmptyAccounts = false;

          // this.sales_account_items.map((item) => {
          //   if (!item.account || item.collection_amount === "" || item.collection_amount === null) {
          //     ifHasEmptyAccounts = true;
          //   }
          // });
          // if (ifHasEmptyAccounts) {
          //   this.$message.warn("请将结算账户信息填写完整");
          //   return false;
          // }

          if (this.materialItems.length == 0) {
            this.$message.warn("未添加产品");
            return false;
          }
          this.materialItems.map((item) => {
            if (item.sales_price === null || !item.sales_quantity) {
              ifHasEmptyGoods = true;
            }
          });
          if (ifHasEmptyGoods) {
            this.$message.warn("销售单价和销售数量必填");
            return false;
          }

          let sales_account_items = [];
          if (this.sales_account_item.account && this.sales_account_item.collection_amount > 0) {
            sales_account_items = [this.sales_account_item];
          }

          this.loading = true;
          let formData = {
            ...this.form,
            // sales_account_items: this.sales_account_items.map((item) => {
            //   delete item.id;
            //   return item;
            // }),
            sales_account_items,
            sales_goods_items: this.materialItems.map((item) => {
              return {
                goods: item.goods,
                sales_quantity: item.sales_quantity,
                sales_price: item.sales_price,
                guige:item.guige,
                chicun:item.chicun,
                huchang:item.huchang,
                clsl:item.clsl,
                cldj:item.cldj,
                clAmount:item.clAmount,
                jgsl:item.jgsl,
                jgdj:item.jgdj,
                jgAmount:item.jgAmount,
                totalAmount:item.totalAmount,
                beizhu:item.beizhu
              };
            }),
          };
          console.log('formData',formData)
          saleOrderCreate(formData)
            .then((data) => {
              this.$message.success("创建成功");
              this.$router.push({ path: "/sale/sale_record" });
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
    resetForm() {
      this.form = { other_amount: 0};
      this.sales_account_item = { collection_amount: 0 };
      getSaleOrderNumber().then((data) => {
        this.form = {...this.form, number: data.number, discount: 100 };
      });
      this.materialItems = [];
      this.handelAddAcount();
    },
  },
  mounted() {
    this.initData();
  },
};
</script>
